<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item :label="$t('设备编码')">
              <a-input :placeholder="$t('请输入设备编码')" v-model="queryParam.deviceId"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item :label="$t('设备名称')">
              <a-input :placeholder="$t('请输入设备名称')" v-model="queryParam.name"></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('机号')">
                <a-input :placeholder="$t('请输入机号')" v-model="queryParam.machineNo"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('绑定项目')">
                <a-select
                  v-model="queryParam.game"
                  show-search
                  :placeholder="$t('请输入绑定项目')"
                  :default-active-first-option="false"
                  :show-arrow="false"
                  :filter-option="false"
                  :not-found-content="null"
                  :options="gameList"
                  @search="handleSearch"
                ></a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('投币外设')">
                <j-dict-select-tag :placeholder="$t('请选择')" v-model="queryParam.inputPeri" dictCode="yn"/>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('退票外设')">
                <j-dict-select-tag :placeholder="$t('请选择')" v-model="queryParam.outputPeri" dictCode="yn"/>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24" v-if="!tenantId">
              <a-form-item :label="$t('门店')">
                <a-select v-model="queryParam.tenantId">
                  <a-select-option v-for="(item, i) in shops" :key="i" :value="item.value"
                    >{{ item.title }}<span v-if="item.value != ''">（{{ item.value }}）</span></a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">{{ $t('查询') }}</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">{{
                $t('重置')
              }}</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? $t('收起') : $t('展开') }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-popconfirm v-has="'DevicePeriCert:edit'" :title="$t('确定启用所有的投币外设和退票外设吗?')" @confirm="() => batchCert(1, 1, 1)">
        <a-button type="primary">{{ $t('一键全部启用') }}</a-button>
      </a-popconfirm>
      <a-button v-has="'DevicePeriCert:edit'" type="primary" @click="batchCert(1, null, 0)" style="margin-left: 8px">{{ $t('批量启用投币外设') }}</a-button>
      <a-button v-has="'DevicePeriCert:edit'" type="primary" @click="batchCert(0, null, 0)" style="margin-left: 8px">{{ $t('批量禁用投币外设') }}</a-button>
      <a-button v-has="'DevicePeriCert:edit'" type="primary" @click="batchCert(null, 1, 0)" style="margin-left: 8px">{{ $t('批量启用退票外设') }}</a-button>
      <a-button v-has="'DevicePeriCert:edit'" type="primary" @click="batchCert(null, 0, 0)" style="margin-left: 8px">{{ $t('批量禁用退票外设') }}</a-button>
    </div>

    <!-- table区域-begin -->
    <div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无图片') }}</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无文件') }}</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            {{ $t('下载') }}
          </a-button>
        </template>
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)" v-has="'DevicePeriCert:edit'" style="margin-left: 7px">{{ $t('编辑') }}</a>
        </span>
      </a-table>
    </div>
    <device-peri-cert-modal ref="modalForm" @ok="modalFormOk"/>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import Vue from 'vue'
import QRCode from 'qrcodejs2'
import { getAction, putAction, deleteAction, httpAction } from '@/api/manage'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import DevicePeriCertModal from './modules/DevicePeriCertModal'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'

export default {
  name: 'DevicePeriCert',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    DevicePeriCertModal,
  },
  data() {
    return {
      description: '外设授权管理页面',
      // 表头
      columns: [
        {
          title: this.$t('门店编码'),
          align: 'center',
          sorter: true,
          dataIndex: 'tenantId',
        },
        {
          title: this.$t('门店名称'),
          align: 'center',
          dataIndex: 'tenantId_dictText',
        },
        {
          title: this.$t('设备编码'),
          align: 'center',
          dataIndex: 'deviceId',
        },
        {
          title: this.$t('设备名称'),
          align: 'center',
          sorter: true,
          dataIndex: 'name',
        },
        {
          title: this.$t('机号'),
          align: 'center',
          sorter: true,
          dataIndex: 'machineNo',
        },
        {
          title: this.$t('绑定娱乐项目'),
          align: 'center',
          dataIndex: 'game_dictText',
        },
        {
          title: this.$t('投币外设'),
          align: 'center',
          sorter: true,
          dataIndex: 'inputPeri_dictText',
        },
        {
          title: this.$t('退票外设'),
          align: 'center',
          sorter: true,
          dataIndex: 'outputPeri_dictText',
        },
        {
          title: this.$t('操作'),
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/device/bisDeviceInfo/list',
        delete: '/device/bisDeviceInfo/delete',
        deleteBatch: '/device/bisDeviceInfo/deleteBatch',
        exportXlsUrl: '/device/bisDeviceInfo/exportXls',
        importExcelUrl: 'device/bisDeviceInfo/importExcel',
      },
      dictOptions: {},
      superFieldList: [],
      qrVisible: false,
      info: {},
      gameList: [],
      selectedRowKeys: [],
      selectionRows: [],
      deviceTypeList: [],
      queryParam: {
        kind: 2,
        type: 'T10P',
        tenantId: ''
      },
      shops:[],
      tenantId: Vue.ls.get('TENANT_ID'),
      isCustom: true,
    }
  },
  created() {
    if(!this.tenantId){
      initDictOptions('bis_shop,name,code').then((res) => {
        if (res.success) {
          this.shops = res.result
          this.shops.unshift({ value: '', title: this.$t('全部') })
        }
      })
    }
    if (this.tenantId) {
      this.columns = this.columns.filter((o) => {
        return o.dataIndex != 'tenantId' && o.dataIndex != 'tenantId_dictText'
      })
    }
    this.$set(this.dictOptions, 'currencyManage', [
      { text: this.$t('是'), value: 'Y' },
      { text: this.$t('否'), value: 'N' },
    ])
    this.handleSearch('')
    if (this.$route.query.game) {
      this.queryParam.game = this.$route.query.game
    } else {
      delete this.queryParam.game
    }
    this.loadData(1)
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  watch: {
    $route(to, form) {
      if (this.$route.query.game) {
        this.queryParam.game = this.$route.query.game
      } else {
        delete this.queryParam.game
      }
      this.loadData(1)
    },
  },
  methods: {
    initDictConfig() {
      getAction('device/bisDeviceInfo/getTypeList', { kind: 2 }).then((res) => {
        if (res.success) {
          this.deviceTypeList = res.result.records
        }
      })
    },
    handleEdit(record){
      this.$refs.modalForm.edit(record);
      this.$refs.modalForm.title = this.$t('编辑');
      this.$refs.modalForm.disableSubmit = false;
    },
    modalFormOk() {
      this.loadData(this.ipagination.current)
      this.onClearSelected()
    },
    handleDevice(record) {
      this.qrVisible = true
      this.info = record
    },
    handleCancel() {
      this.qrVisible = false
    },
    handleSearch(value) {
      let query = {}
      query.gameInfo = value
      query.pageNo = 1
      query.pageSize = 99
      getAction('/game/bisGame/list', query).then((res) => {
        if (res.success) {
          this.gameList = []
          res.result.records.forEach((r) => {
            this.gameList.push({
              value: r.id,
              label: r.name,
            })
          })
        }
      })
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    batchAssign() {
      if (this.selectedRowKeys.length > 0) {
        this.$refs.modalForm1.edit(this.selectedRowKeys)
      } else {
        this.$message.warning(this.$t('请先选择要操作的设备'))
      }
    },
    batchOpen() {
      if (this.selectedRowKeys.length > 0) {
        let queryList = []
        this.selectedRowKeys.forEach((item) => {
          let aa = {}
          aa.id = item
          aa.state = 0
          queryList.push(aa)
        })
        putAction('/device/bisDeviceInfo/updateBatch', queryList).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.modalFormOk()
          } else {
            this.$message.warning(res.message)
          }
        })
      } else {
        this.$message.warning(this.$t('请先选择要操作的设备'))
      }
    },
    batchClose() {
      if (this.selectedRowKeys.length > 0) {
        let queryList = []
        this.selectedRowKeys.forEach((item) => {
          let aa = {}
          aa.id = item
          aa.state = 1
          queryList.push(aa)
        })
        putAction('/device/bisDeviceInfo/updateBatch', queryList).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.loadData(this.ipagination.current)
            this.modalFormOk()
          } else {
            this.$message.warning(res.message)
          }
        })
      } else {
        this.$message.warning(this.$t('请先选择要操作的设备'))
      }
    },
    batchDel: function () {
      let that = this
      if (that.selectedRowKeys.length <= 0) {
        that.$message.warning(that.$t('请先选择要删除的设备'))
      } else {
        let ids = that.selectedRowKeys.join(',')
        that.$confirm({
          title: that.$t('确认'),
          content: that.$t('您确定要将已选择的设备从列表中清空吗？ '),
          okText: that.$t("确定"),
          cancelText: that.$t("取消"),
          onOk: function () {
            that.loading = true
            deleteAction(that.url.deleteBatch, { ids: ids }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData(1)
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
          }
        })
      }
    },
    searchReset() {
      this.queryParam = {
        kind: 2,
        type: 'T10P',
        tenantId: ''
      }
      this.searchQuery()
    },
    batchCert(inputPeri, outputPeri, option){
      if (this.selectedRowKeys.length > 0 || option === 1) {
        let query = {
          id: this.selectedRowKeys.length > 0? this.selectedRowKeys.join(","):"",
          inputPeri: inputPeri,
          outputPeri: outputPeri
        }
        putAction('/device/bisDeviceInfo/batchCert', query).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.loadData(this.ipagination.current)
            this.modalFormOk()
          } else {
            this.$message.warning(res.message)
          }
        })
      } else {
        this.$message.warning(this.$t('请先选择要操作的设备'))
      }
    },
    batchQrcode() {
      if (this.selectedRowKeys.length > 0) {
        this.getQrcodeUrl(0)
      }
    },
    getQrcodeUrl(i) {
      let that = this
      getAction('/device/bisDeviceInfo/qrCode', { deviceId: that.selectionRows[i].deviceId }).then((res) => {
        if (res.success) {
          that.$set(that.selectionRows[i], 'url', res.result)
        }
        i++
        if (i < that.selectionRows.length) {
          that.getQrcodeUrl(i)
        } else {
          that.printManyQrcode()
        }
      })
    },
    printManyQrcode() {
      // assetsArr 需要打印二维码的内容数据
      let assetsArr = this.selectionRows
      if (assetsArr.length) {
        var iframeDom = window.open('') // 打开一个空白的页面，使用变量iframeDom接受
        var dom = `<div style="display: flex; flex-wrap: wrap">` // 拼接的字符串
        assetsArr.forEach((item, i) => {
          // 拼接DOM元素，这里需要注意的是div的id元素，其实是咱们用来找到打印内容的锚点；样式需要直接写在DOM元素的style属性里面
          dom += `<div
          style="
            width: 41mm;
            height: 41mm;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            border: 1px solid #000;
            margin-bottom: 12px;
            margin-right: 12px;
            box-sizing: border-box;
          "
        >
          <div id="code${item.id}" ref="code${item.id}" class="code"></div>
          <div style="color: #000; font-weight: 600; text-align: center;font-size:12px">
            <span>${item.deviceId}</span><span style="padding-left: 6px">No. ${item.machineNo}</span>
          </div>
        </div>`
        })
        dom += `</div>`
        iframeDom.document.write(dom) // 添加到页面
        setTimeout(()=> {
          // 添加一个延时是为了能获取到页面上的dom元素
          assetsArr.forEach((item) => {
            var qrcodeDom = iframeDom.document.getElementById('code' + item.id) // 这里必须是iframeDom.document.……才能获取到元素，不能直接document.
            new QRCode(qrcodeDom, {
              text: item.url, // 需要转换为二维码的内容
              width: 120,
              height: 120,
            })
          })
          setTimeout(()=> {
            // 添加延时为了让页面的内容呢渲染完
            iframeDom.document.title = '批量二维码打印' // 设置页面标题
            iframeDom.print()
            iframeDom.close()
            this.onClearSelected()
          }, 100)
        }, 10)
      }
    },
    batchEdit() {
      if (this.selectedRowKeys.length > 0) {
        this.$refs.editModal.edit(this.selectedRowKeys)
      } else {
        this.$message.warning(this.$t('请先选择要操作的设备'))
      }
    },
    getParameter() {
      getAction('/bis/bisSysParameter/list', { name: 'defaultDeviceStart' }).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            this.defaultDeviceStart = res.result.records[0]
            this.defaultDeviceStart.ivalues = this.defaultDeviceStart.ivalue ? true : false
          } else {
            this.defaultDeviceStart = { name: 'defaultDeviceStart', ivalue: 1, comment: '新设备默认启用' }
            this.defaultDeviceStart.ivalues = true
          }
        }
      })
    },
    parameterChange() {
      let that = this,
        querydata = {}
      let url = '',
        method = ''
      if (that.defaultDeviceStart.id) {
        url = '/bis/bisSysParameter/edit'
        method = 'put'
      } else {
        url = '/bis/bisSysParameter/add'
        method = 'post'
      }
      if (that.defaultDeviceStart.ivalues === true) {
        that.defaultDeviceStart.ivalue = 1
      } else {
        that.defaultDeviceStart.ivalue = 0
      }
      querydata = Object.assign({}, that.defaultDeviceStart)
      httpAction(url, querydata, method).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.getParameter()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>